package genedit.controller.interfaceActions;

import genedit.gui.GMainFrame;
import genedit.gui.GProjectTree;
import genedit.model.HierarchyElement;
import genedit.model.Project;
import genedit.model.Workspace;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.KeyStroke;

/**
 * Akcija zadužena za zatvaranje izabranog projekta. Prilikom zatvaranja se
 * poziva akcija za čuvanje dokumenta.
 * 
 * @see GSaveA
 * @author Nikola
 * @version 1.1 10/11/13
 */
public class GCloseA extends AbstractAction {
	private static final long serialVersionUID = 1L;

	private static GCloseA instance;

	public GCloseA() {
		putValue(NAME, "Close");
		putValue(SHORT_DESCRIPTION, "Close");
		putValue(SMALL_ICON, new ImageIcon("resources/icons/close.png"));
		putValue(MNEMONIC_KEY, KeyEvent.VK_L);
		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("control W"));
	}

	public static GCloseA getInstance() {
		if (instance == null)
			instance = new GCloseA();
		return instance;
	}

	/**
	 * Akcija čuva izabrani projekat, zatim ga uklanja iz stabla hijerarhije i
	 * zatvara sve prozore koji su pripadali dijagramima datog projekta, ukoliko
	 * ih je bilo.
	 */
	public void actionPerformed(ActionEvent arg0) {
		HierarchyElement element = (HierarchyElement) GProjectTree.getInstance().getTree()
				.getLastSelectedPathComponent();
		if (element instanceof Workspace)
			return;

		GSaveA.getInstance().actionPerformed(arg0);

		while (!(element instanceof Project))
			element = (HierarchyElement) element.getParent();

		Project project = (Project) element;
		Workspace.getInstance().removeProjects(project);
		GMainFrame.getInstance().closeViewsOfClosedDocuments((HierarchyElement) project);
	}

}